<template>
  <div></div>
</template>
<script lang="ts" setup>
import { inject, computed, watch, ref, onMounted, nextTick, reactive } from 'vue';
import { getStaticFile } from '@sutpc/axios';
import { useUserStore } from '@/store/user'
import { id } from 'element-plus/es/locale';
import { getFileByStatic} from '@/utils/index';
import { getTiannetApi } from '@/utils/api'

defineOptions({
  name: 'AcIndexLayer',
  
});
const { hooks, mapInstance, AC_NAME, MARS3D_NAME, useEmitt: acUseEmitt }: any = inject('main');

const userStore = useUserStore()
// 创建坪山区域polygon图形
const getPingshan = async () => {
  mapInstance.value.acApi.polygon.clear();
  await getStaticFile('[publicPath]static/jsons/pingshan-mars.json').then((jsonData) => {
    const coordinates = jsonData.features[0].geometry.coordinates[0]
    let psPolygon = {
      id: 'pingshan',
      groupId: 'pingshanGroup',
      coordinates,
      coordinateType: 1, //坐标系类型，取值范围：0为Projection类型，1为WGS84类型，2为火星坐标系(GCJ02)，3为百度坐标系(BD09)，默认值：0
      range: [1, 100000], //可视范围：[近裁距离, 远裁距离]，取值范围: [任意负值, 任意正值]
      color: [0.13, 0.65, 0.73, 0.8], //多边形的填充颜色
      frameColor: '#ffffff', //边框颜色
      frameThickness: 50, //边框厚度
      intensity: 100, //亮度
      style: PolygonStyle.SingleColor, //单色 请参照API开发文档选取枚举
      depthTest: false //是否做深度检测 开启后会被地形高度遮挡
    }
    let pArr = [];
    pArr.push(psPolygon);
    mapInstance.value.acApi.polygon.add(pArr)
    mapInstance.value.acApi.polygon.focus('pingshan', 10000);
    userStore.isShowMenu(false)
  })
}
// 删除坪山区域polygon
const deletePsPolygon = () => {
  mapInstance.value.acApi.polygon.delete('pingshan')
}

var vehicleDataMap = new Map();
var moveVehicleDataMap = new Map();
// 设置定时器监听
let timer = ref<ReturnType<typeof setTimeout>>()
// 点击坪山区域后的回调
acUseEmitt("AIRCITY_EVENT", async (e) => {
  if (e.UserData) {
    const userData = JSON.parse(e.UserData)
    // 点击雷达图标获取雷达感知
    if (userData.typeId === 103) {
      mapInstance.value.acApi.radiationPoint.add({
        id: e.Id,
        groupId: e.GroupID,
        coordinate: [e.MouseClickPoint[0], e.MouseClickPoint[1], 40],
        radius: 10,
        rippleNumber: 2,
        color: '#FFFEEE',
        intensity: 0.5,
        autoHeight: true
      })
    }
    // 获取通行方向车道
    if (userData.typeId === 101) {
      mapInstance.value.acApi.polygon.add({
        id: e.Id,
        groupId: e.GroupID,
        userData,
        depthTest: false,
        color: '#13C6E6',
        coordinates: [[114.30767000315753,22.675083394082645, 60],[114.30748223681546,22.67554362999737, 60], [114.3073274564024,22.675494922012426, 60], [114.30755217141629,22.675034619334145, 60], ],
        coordinateType: 1,
        style: 5
      })
    }
  }
  // 获取雷达感知
  if (e.GroupID === 'pingshanGroup') {
    deletePsPolygon()
    mapInstance.value.acApi.camera.get((r) => {
      var str = `Camera: ${r.x}, ${r.y}, ${r.z}, ${r.pitch}, ${r.yaw}`;
     //或者这样调用
    //  var str = `Camera: ${r.camera.join(',')}`;
    //  console.log(str);
    })
    // 定位指定路口，同时显示顶部路口设备模块
    mapInstance.value.acApi.camera.set(531636.8475, 2508556.124375, 174.407129, -83.974602, -114.262474, () => {
      userStore.isShowMenu(true)
      topicVehicle()
      equAdd()
      // openTimer()
    })
    // mapInstance.value.acApi.marker.focus('test', 100)
  }
})
// watch(flag, (newVal) => {
//   console.log(newVal)
// })
// 创建设备图标
const equAdd = () => {
  // 调用路口路测设备接口
  getTiannetApi().then((jsonData) => {
    // equList.value = jsonData
    // console.log(equList.value)
    userStore.setEquList(jsonData)
    userStore.setEquId(jsonData[0].typeId)
    mapInstance.value.acApi.marker.add(createMarkerData(userStore.equList[0].childs))
  })
}
// 清除雷达感知
const clearPerception = () => {
  mapInstance.value.acApi.radiationPoint.clear()
}
// 根据设备id定义创建marker时的数据
const createMarkerData = (data) => {
  const arr = []
  data.map((item) => {
    let obj = {
      id: item.id,
      groupId: `${item.id}`,
      userData: JSON.stringify(item),
      coordinateType: 1,
      coordinate: [item.lat, item.lon, 40],
      anchors: [15, 55],
      imageSize: [30, 55],
      fixedSize: false,
      imagePath: '',
      displayMode: 2
    }
    if (item.typeId === 101) {
      obj.imagePath = getFileByStatic('images/icon_xinhaodeng.png')
    }
    if (item.typeId === 102) {
      obj.imagePath = getFileByStatic('images/icon_shexiangji.png')
    }
    if (item.typeId === 103) {
      obj.imagePath = getFileByStatic('images/icon_leida.png')
    }
    if (item.typeId === 104) {
      obj.imagePath = getFileByStatic('images/icon_rsu.png')
    }
    if (item.typeId === 105) {
      obj.imagePath = getFileByStatic('images/icon_mec.png')
    }
    arr.push(obj)
  })
  return arr
}
// 更新设备点位 用于切换对应设备点位位置、icon、数据
const equUpdate = (data) => {
  mapInstance.value.acApi.marker.clear()
  mapInstance.value.acApi.marker.add(createMarkerData(data.childs))
}



const vehicleData = computed(() => {
  return userStore.vehicleData
})
// 声明删除
let delArr = []
// 声明所有创建的车辆
const allVehicle = ref([])
// 监听车辆数据变化，如果没有创建新车辆，如果有了更新车辆数据
watch(vehicleData, async (newVal) => {
  if (newVal) {
    // 如果有新增车辆
    if (newVal.add.length !== 0) {
      await mapInstance.value.acApi.vehicle.add(newVal.add, (e) => {
        // 创建车辆成功后，如果allVehicle里没有创建的车辆，就把创建的车辆保存到allVehicle里
        newVal.add.forEach(item => {
          if (!allVehicle.value.includes(item.id)) {
            allVehicle.value.push(item.id)
          }
        })
      })
    }
    // 如果传入车辆移动点位
    if (newVal.moveTo.length !== 0) {
      console.log(newVal.moveTo)
      await mapInstance.value.acApi.vehicle.moveTo(newVal.moveTo, (e) => {
        let moveToIds = newVal.moveTo.map(item => item.id)
        for (let i = allVehicle.value.length - 1; i >= 0; i--) {
          if (!moveToIds.includes(allVehicle.value[i])) {
            delArr.push(allVehicle.value[i])
            allVehicle.value.splice(i, 1)
          }
        }
        mapInstance.value.acApi.vehicle.delete(delArr, () => {
          console.log(delArr)
          delArr = []
        })
      })
    }



    // if(vehicleDataMap.get(vehicleData.value.id)){//更新点位
      
    //   // moveVehicleDataMap.set(vehicleData.value.id, {
    //   //   id: String(vehicleData.value.id),
    //   //   coordinate: [Number(vehicleData.value.lon), Number(vehicleData.value.lat), 40],
    //   //   gear: 3,
    //   //   time: 1
    //   // });
    //   // mapInstance.value.acApi.vehicle.moveTo({
    //   //   id: String(vehicleData.value.id),
    //   //   coordinate: [Number(vehicleData.value.lon), Number(vehicleData.value.lat), 40],
    //   //   gear: 3,
    //   //   time: 2
    //   // });
    //   mapInstance.value.acApi.vehicle.moveTo({
    //     id: String(vehicleData.value.id),
    //     coordinate: [Number(vehicleData.value.lon), Number(vehicleData.value.lat), 40],
    //     gear: 3,
    //     time: 1
    //   }, () => {
    //     console.log('moveTo调用成功')
    //   })
    // } else {//没有找到车，创建
    //   var t1 = Number(new Date().getTime());
    //   let obj = {
    //     id: String(vehicleData.value.id),
    //     assetPath: '/JC_CustomAssets/VehicleLibrary/Exhibition/SUV_01',
    //     coordinate: [Number(vehicleData.value.lon), Number(vehicleData.value.lat), 40],
    //     coordinateType: 1,
    //     autoHeight: true
    //   }
    //   mapInstance.value.acApi.vehicle.add(obj)
    //   // mapInstance.value.acApi.vehicle.add(obj, function(){
    //   //   console.log(Number(new Date().getTime()) - t1);
    //   // });
    //   vehicleDataMap.set(vehicleData.value.id, vehicleData);
    // }
  }
})
const openTimer = () => {
  timer.value = setInterval(()=>{
    var moveArr = Array.from(moveVehicleDataMap.values());
    // for (const [key, value] of moveVehicleDataMap) {
    //   // console.log(nowTime, value);
    //   moveArr.push({
    //     id: String(value.value.id),
    //     coordinate: [Number(value.value.lon), Number(value.value.lat), 40],
    //     gear: 3,
    //     time: 1
    //   });
    // }

    // mapInstance.value.acApi.vehicle.moveTo(moveArr, moveEnd(value.value.id));
    mapInstance.value.acApi.vehicle.moveTo(moveArr);

    // console.log('数组' + delArr)
    // delArr.forEach((i)=>{
    //   console.log('ID' + i)
    //   mapInstance.value.acApi.vehicle.delete(i);
    //   vehicleDataMap.delete(i);
    // })
  }, 1000)
}
const moveEnd = (vhicleIds)=>{
  // console.log(vhicleIds.slice(-1)[0])
  // vhicleIds.forEach((item) => {
    vehicleDataMap.delete(vhicleIds.slice(-1)[0]);
    mapInstance.value.acApi.vehicle.delete(vhicleIds.slice(-1)[0].id);
  // });
  
};
// const delVehicle = setInterval(()=>{
//   console.log("dingshiqi")
//   var nowTime =  Number(new Date().getTime);
//   var delArr = [];
//   for (const [key, value] of vehicleDataMap) {
//     if(nowTime - value>=500){
//       delArr.push(key);

//       console.log(key)
//     }
//   }
//   delArr.forEach((i)=>{
//     mapInstance.value.acApi.vehicle.delete(i);
//     vehicleDataMap.delete(i);
//   })
// }, 2000);
// 创建车辆
// const createVehicle = async (dataArr) => {
//   const vehicles = []
//   for (let i in dataArr) {
//     let obj = {
//       id: dataArr[i].id,
//       groupId: dataArr[i].id,
//       userData: dataArr[i],
//       assetPath: '/JC_CustomAssets/VehicleLibrary/Exhibition/SUV_01',
//       coordinate: [Number(dataArr[i].lon), Number(dataArr[i].lat), 40],
//       coordinateType: 1,
//       autoHeight: true
//     }
//     vehicles.push(obj)
//   }
//  await  mapInstance.value.acApi.vehicle.add(vehicles)
// }
// 设置车辆行驶
// const vehicleMoveTo = () => {
//   const moveToArr = []
//   vehicleArr.forEach(item => {
//     // const found = dataArr.find(item1 => item1.id === item.id)
//     // if (found) {
//       // console.log(item)
//       moveToArr.push({
//         id: String(item.id),
//         coordinate: [Number(item.lon), Number(item.lat), 40],
//         gear: 3,
//         time: 1
//       })
//     // }
//   })
//   // console.log(moveToArr)
//   mapInstance.value.acApi.vehicle.moveTo(moveToArr)
// }
// 删除车辆
// const deleteVehicle = (dataArr) => {
//   const vehicleIds = []
//   vehicleArr.forEach(item => {
//     const found = dataArr.find(item1 => item1.id === item.id)
//     if (!found) {
//       vehicleIds.push(item.id)
//       console.log(vehicleIds)
//       mapInstance.value.acApi.vehicle.delete(vehicleIds)
//     }
//   })
// }
// 清空场景中所有Vehicle对象
const clearVehicle = async () => {
  await mapInstance.value.acApi.vehicle.clear(() => {
    userStore.closeMqttClient()
  })
}
// 订阅路口车流数据
const topicVehicle = () => {
  userStore.initMqttVehicle('ROAD-035')
}
// 删除设备点位
const equDelete = () => {
  mapInstance.value.acApi.marker.clear()
  getPingshan()
}
// onMounted(()=>{
//   getPingshan()
// })
defineExpose({
  getPingshan,
  clearVehicle,
  equDelete,
  equUpdate,
  clearPerception
})
</script>
<style lang="less" scoped></style> 